package com.isunland.managesystem.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseNetworkDialogFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.CustomerNeed;
import com.isunland.managesystem.entity.CustomerNeedOriginal;
import com.isunland.managesystem.utils.LogUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONException;

/**
 * 对象功能:
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: HuXiaoDan
 * 创建时间: 2017/3/13 15:17
 */
public class CustomerNeedListDialogFragment extends DialogFragment {

  protected static final String TAG = BaseNetworkDialogFragment.class.getSimpleName();
  /** 回传对象f */
  public static final String EXTRA_VALUE =
      "com.isunland.managesystem.ui.CustomerNeedListDialogFragment.extra_value";
  public static final String EXTRA_CODE =
      "com.isunland.managesystem.ui.CustomerNeedListDialogFragment.extra_value";
  private BaseVolleyActivity mActivity;

  private ArrayAdapter<CustomerDialog> mAdapter;

  private AlertDialog mDialog;
  private List<CustomerNeed> dataList = new ArrayList<>();
  private String nameId;

  @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) {

    AlertDialog.Builder builderSingle = new AlertDialog.Builder(getActivity());
    View v = getActivity().getLayoutInflater().inflate(R.layout.dialog_progress, null);
    builderSingle.setView(v);
    mDialog = builderSingle.create();
    return mDialog;
  }

  @Override public void onCreate(Bundle savedInstanceState) {

    mActivity = (BaseVolleyActivity) getActivity();
    //客户id
    nameId = getArguments().getString(EXTRA_CODE);
    volleyPost();
    super.onCreate(savedInstanceState);
  }

  private void volleyPost() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_CUSTOMER_NEED_LIST);
    HashMap<String, String> params = getparameters();
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        ArrayList<CustomerDialog> list = resolveResponse(arg0);

        if (list == null || list.size() == 0) {
          emptyToast();
          mDialog.dismiss();
          return;
        }
        setAdapter(list);
      }

      @Override public void onVolleyError(VolleyError arg0) {
      }
    });
  }

  /** 获取参数列表 */
  public HashMap<String, String> getparameters() {
    HashMap<String, String> params = new HashMap<>();
    params.put("customerId", nameId);
    return params;
  }

  /**
   * 当列表数据为空时的自定义提示。默认提示“空数据”。 重写这个方法的时候不要调用super。
   */
  protected void emptyToast() {
    Toast.makeText(getActivity(), R.string.empty_data, Toast.LENGTH_SHORT).show();
  }

  /**
   * 解析响应,将相应解析成对象后必须重新封装成CustomerDialog列表.
   *
   * @param arg0 服务器获取的json数据
   */
  public ArrayList<CustomerDialog> resolveResponse(String arg0) {
    ArrayList<CustomerDialog> list = new ArrayList<>();

    CustomerNeedOriginal contractContentOriginal =
        new Gson().fromJson(arg0, CustomerNeedOriginal.class);

    dataList = contractContentOriginal.getRows();

    if (dataList == null || dataList.size() == 0) {

      return null;
    }
    for (int i = 0; i < dataList.size(); i++) {
      list.add(new CustomerDialog(dataList.get(i).getNeedProductDesc(), dataList.get(i).getId()));
    }
    return list;
  }

  private void setAdapter(ArrayList<CustomerDialog> customerDialogs) {
    mDialog.dismiss();

    if (mAdapter == null) {
      if (null == getActivity()) {
        return;
      }

      mAdapter = new ArrayAdapter<CustomerDialog>(getActivity(),
          android.R.layout.select_dialog_singlechoice, customerDialogs) {

        @Override public View getView(int position, View convertView, ViewGroup parent) {
          CustomerDialog user = getItem(position);
          if (convertView == null) {
            convertView = LayoutInflater.from(getContext())
                .inflate(android.R.layout.simple_list_item_1, parent, false);
          }
          TextView tvName = (TextView) convertView.findViewById(android.R.id.text1);

          tvName.setText(Html.fromHtml(user.getName()));

          return convertView;
        }
      };
    } else {
      mAdapter.clear();
      mAdapter.addAll(customerDialogs);
    }

    AlertDialog.Builder builderSingle = new AlertDialog.Builder(getActivity());
    builderSingle.setAdapter(mAdapter, new DialogInterface.OnClickListener() {

      @Override public void onClick(DialogInterface dialog, int which) {
        CustomerDialog customerDialog = mAdapter.getItem(which);
        CustomerNeed data = dataList.get(which);

        if (getTargetFragment() == null) return;
        Intent i = new Intent();
        //                i.putExtra(EXTRA_VALUE, customerDialog);
        i.putExtra(EXTRA_VALUE, data);
        LogUtil.i("customerDialog===" + customerDialog);
        getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, i);
      }
    });
    builderSingle.create().show();
  }

  public static CustomerNeedListDialogFragment newInstance(String customerId) {

    Bundle args = new Bundle();
    args.putString(EXTRA_CODE, customerId);
    CustomerNeedListDialogFragment fragment = new CustomerNeedListDialogFragment();
    fragment.setArguments(args);
    return fragment;
  }
}
